﻿using Api.Application.Command.User;
using AutoMapper;
using Domain;
using ErrorCode;
using Infrastructure;
using MediatR;
using Yitter.IdGenerator;

namespace Api.Application.Handler.User
{
    public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, ApiResult<int>>
    {
        private readonly IBase<UserModel> userRepo;
        private readonly IMapper mapper;

        public UpdateUserHandler(IBase<UserModel> userRepo, IMapper mapper)
        {
            this.userRepo = userRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var user = userRepo.GetAll().Where(x => x.Id == request.Id).FirstOrDefault();
            if (user == null)
            {
                result.Msg = "要修改的用户不存在";
                result.Code = ApiEnum.Fail;
                return Task.FromResult(result);
            }
            var users = userRepo.GetAll().Where(x => x.UserName == request.UserName).Count();
            if (users > 0)
            {
                result.Msg = "该用户已存在";
                result.Code = ApiEnum.Fail;
                return Task.FromResult(result);
            }
            var model = mapper.Map(request, user);
            model.UpdateName = "李四";
            model.UpdateTime = DateTime.Now;
            var r = userRepo.Update(model).Result;
            if (r > 0)
            {
                result.Msg = "修改成功";
                result.Code = ApiEnum.OK;
                result.Data = r;
            }
            else
            {
                result.Msg = "修改失败";
                result.Code = ApiEnum.Fail;
                result.Data = r;
            }
            return Task.FromResult(result);
        }
    }
}
